#include <stdio.h>
#include <memory>
#ifdef WIN32
#include <string.h>
#else
#include <strings.h>
#endif
#include <gtest/gtest.h>
#include <hiredis/hiredis.h>
#include <libgo/coroutine.h>


#define O(x) std::cout << x << std::endl

namespace hiredis {

    void do_redis(int num) {
        redisContext* redis_ctx = redisConnect("127.0.0.1", 6379);
        if (!redis_ctx) {
            O("[" << num << "] connect error");
            return;
        }

        if (redis_ctx->err) {
            O("[" << num << "] connect error " << redis_ctx->err);
            return;
        }

        O("[" << num << "] connected redis.");
        std::shared_ptr<redisContext> _ep(redis_ctx, [](redisContext * c) { redisFree(c); });

        const char* cmd_set = "set i 1";
        redisReply* reply = (redisReply*)redisCommand(redis_ctx, cmd_set);
        if (!reply) {
            O("[" << num << "] reply is NULL.");
            return;
        }

        //printf("[%d] got reply.\n", num);
        std::shared_ptr<redisReply> _ep_reply(reply, [](redisReply * reply) { freeReplyObject(reply); });

        if (!(reply->type == REDIS_REPLY_STATUS && strcasecmp(reply->str, "OK") == 0)) {
            O("[" << num << "] execute command error.");
            return;
        }
        O("[" << num << "] execute command success.");
    }
}

TEST(hiredis, test) {
    using namespace hiredis;

    for (int i = 0; i < 2; ++i) {
        go[=] { do_redis(i); };
    }

    co_sched.Start();
}
